<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Http\Controllers\Controller;
use App\Models\AgentUser;
use App\Models\Product;
use App\Models\Store;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;

class StoreController extends Controller
{
    /** 门店列表 */
    public function index()
    {
        /** @var AgentUser $user */
        $user = auth()->user();
        $query = Store::query()->where('agent_id', $user->agent_id)
            ->orderByDesc('is_default')
            ->orderByDesc('id');

        return paginate_result($query);
    }

    /** 保存门店信息 */
    public function store()
    {
        request()->validate([
            'name' => 'required',
            'mobile' => 'required',
            'divide_account' => 'nullable',
            'agent_service_fee_rate' => 'nullable',
        ]);

        /** @var AgentUser $user */
        $user = auth()->user();
        /** @var Store $store */
        $store = get_entity(Store::class);

        $store->agent_id = $user->agent_id;
        $store->name = request()->name;
        $store->mobile = request()->mobile;
        $store->divide_account = request()->divide_account ?: '';
        $store->agent_service_fee_rate = request()->agent_service_fee_rate ?: 0;
        $store->save();
    }

    /** 删除门店 */
    public function destroy($id)
    {
        if (Product::query()->where('store_id', $id)->count() > 0) {
            throw new AdminException('门店下有关联商品，不可删除');
        }
        Store::destroy($id);
    }
}
